//
//  VedioPlayerViewController.m
//  bofangqi
//
//  Created by lanou on 16/6/6.
//  Copyright © 2016年 万长亮. All rights reserved.
//

#import "VedioPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>

#define kHeight [UIScreen mainScreen].bounds.size.height
#define kWidth [UIScreen mainScreen].bounds.size.width
@interface VedioPlayerViewController ()
@property (nonatomic, strong)UISlider *volumeSlider;
@property (nonatomic, strong)UISlider *progressSlider;



@property (nonatomic, strong)UIImageView *picImageView;

@property (nonatomic, strong)UIButton *lastButton;
@property (nonatomic, strong)UIButton *nextButton;
@property (nonatomic, strong)UIButton *playButton;
@property (nonatomic, strong)UILabel *currentTimeLabel;
@property (nonatomic, strong)UILabel *allTimeLabel;

@property (nonatomic, strong)AVPlayer *player;
@property (nonatomic, assign)NSInteger index;
@property (nonatomic, strong)NSArray *vedioArray;


@property (nonatomic, strong)NSTimer *timer;
@end

@implementation VedioPlayerViewController
- (instancetype)initWithFrame:(CGRect )frame array:(NSArray *)videoArray index:(NSInteger)index{
 
    self = [super init];
    if (self) {
        UIView *vedioView = [[UIView alloc]initWithFrame:frame];
        [self.view addSubview:vedioView];
        self.index = index;
        self.vedioArray = videoArray;
//        self.player = [[AVPlayer alloc]init];
        
        self.player = [VedioPlayerViewController shareinstance];
        
        AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player ];
        layer.videoGravity = AVLayerVideoGravityResize;
        layer.frame = frame;
        layer.backgroundColor = [UIColor blackColor].CGColor;
        [vedioView.layer addSublayer:layer];
        self.lastButton = [[UIButton alloc]initWithFrame:CGRectMake(40,kHeight - 50 - 64,30 , 30)];
        self.nextButton = [[UIButton alloc]initWithFrame:CGRectMake(kWidth - 40 - 30, kHeight - 50 - 64, 30, 30)];
        self.playButton = [[UIButton alloc]initWithFrame:CGRectMake(kWidth/2-15, kHeight - 50 - 64, 30, 30)];
        [_lastButton setBackgroundImage:[UIImage imageNamed:@"lastMusic"] forState:(UIControlStateNormal)];
        [_nextButton setBackgroundImage:[UIImage imageNamed:@"nextMusic"] forState:(UIControlStateNormal)];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
        [_lastButton addTarget:self action:@selector(lastButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [_playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [_nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        self.progressSlider = [[UISlider alloc]initWithFrame:CGRectMake(50, kHeight - 80 - 64, kWidth - 100, 30)];
        
        [self.progressSlider addTarget:self action:@selector(progressSliderAction:) forControlEvents:(UIControlEventValueChanged)];
        
        
        [_progressSlider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
        self.currentTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, kHeight - 80 - 64, 40, 30)];
        self.currentTimeLabel.textAlignment = NSTextAlignmentRight;
        self.allTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWidth - 50, kHeight - 80 - 64, 40, 30)];
        self.currentTimeLabel.font = [UIFont systemFontOfSize:14];
        self.allTimeLabel.font = [UIFont systemFontOfSize:14];
        self.currentTimeLabel.textColor = [UIColor whiteColor];
        self.allTimeLabel.textColor = [UIColor whiteColor];
        [self.view addSubview:_allTimeLabel];
        [self.view addSubview:_currentTimeLabel];
        [self.view addSubview:_progressSlider];
        [self.view addSubview:_lastButton];
        [self.view addSubview:_playButton];
        [self.view addSubview:_nextButton];
        
        //  一上来播放视频
        [self replaceItem];
        NSLog(@"%@",self.vedioArray[0][@"url"]);
        //  启动定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        [self.timer fire];
    }
    return self;
}
+ (AVPlayer *)shareinstance{
    static AVPlayer *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[AVPlayer alloc]init];
    });
    return player;
}

- (void)dealloc {
       [NSObject cancelPreviousPerformRequestsWithTarget:self];
}


#pragma mark --- 定时器方法 ---
- (void)timerAction:(NSTimer *)timer{
    
    
    if (self.player.currentTime.timescale == 0 || self.player.currentItem.duration.timescale == 0) {
        return;
    }
    
    long long int currentTime =  self.player.currentTime.value / self.player.currentTime.timescale;
    
    
    long long int allTime = self.player.currentItem.duration.value / self.player.currentItem.duration.timescale;
    
    self.currentTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld",currentTime / 60,currentTime % 60];
    self.allTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld",allTime / 60, allTime % 60];
    //  设置进度条的最大值和总时间相等
    self.progressSlider.maximumValue = allTime;
 
    self.progressSlider.value = currentTime;
    
    // 循环播放
    //    [[playerManager sharIndtance]playerAuto:self.navigationItem];
    [self playerAuto];
}
// 进度条
- (void)progressSliderAction:(UISlider *)slider{
    [self playerProgressWithProgressSliderValue:slider.value];
}

#pragma mark --- 控制进度的方法 ---
- (void)playerProgressWithProgressSliderValue:(CGFloat)value{
    __weak typeof(self) weakSelf = self;
    [weakSelf.player seekToTime:CMTimeMakeWithSeconds(value, 1) completionHandler:^(BOOL finished) {
        [weakSelf playerPlay];
    }];
}
#pragma mark --- 自动播放 ---
//- (void)playerAuto:(UINavigationItem *)item{
- (void)playerAuto{
    if (self.player.currentTime.timescale == 0 || self.player.currentItem.duration.timescale == 0) {
        return;
    }
    
    long long int currentTime =  self.player.currentTime.value / self.player.currentTime.timescale;
    
    
    long long int allTime = self.player.currentItem.duration.value / self.player.currentItem.duration.timescale;
    if (currentTime == allTime) {
        if (self.index == self.vedioArray.count-1) {
            self.index = 0;
            [self replaceItem];
        }else{
            self.index++;
            [self replaceItem];
        }
        
        
        //        item.title = [self findMovieModle].title;
    }
}

//  上一首
- (void)lastButtonAction:(UIButton *)button{
    
    
    if (self.index == 0) {
        self.index = self.vedioArray.count-1;
    }else{
        self.index--;
    }
    
    [self replaceItem];
}
// 播放、暂停
- (void)playButtonAction:(UIButton *)button{
    if (self.playerType == playType) {
        
        [button setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:(UIControlStateNormal)];
        [self playerPause];
    }else{
        [button setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:(UIControlStateNormal)];
        [self playerPlay];
    }
}
// 下一首
- (void)nextButtonAction:(UIButton *)button{
    
    if (self.index == self.vedioArray.count-1) {
        self.index = 0;
    }else{
        self.index++;
    }
    [self replaceItem];
}
#pragma mark --- 播放视频 ---
- (void)replaceItem{

    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:self.vedioArray[_index][@"url"] ]];
    [self.player replaceCurrentItemWithPlayerItem:item];
    [self playerPlay];
}
#pragma  mark --- 在播放 ---
- (void)playerPlay{
    [self.player play];
    self.playerType = playType;
}
#pragma  mark --- 在暂停 ---
- (void)playerPause{
    [self.player pause];
    self.playerType = pauseType;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    // Do any additional setup after loading the view.
    UIBarButtonItem *barbutton = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(backBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem = barbutton;
    
}
- (void)backBarButtonItemAction:(UIBarButtonItem *)sender{
    [_player pause];
    [_timer invalidate];
    _timer = nil;
    _player = nil;

    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
